<template>
    <el-drawer
        size="30%"
        v-model="drawer"
        :title="'添加角色'"
        direction="rtl"
        :before-close="closeDrawer">
        <el-form
        size="small"
        ref="formRef"
        style="max-width: 600px"
        :model="formData"
        status-icon
        :rules="rules"
        label-width="60px"
    >

    <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="选择权限" prop="powerList">
      <el-checkbox-group v-model="formData.powerList">
        <el-checkbox
          v-for="power in allPowerList"
          :key="power.id"
          :label="power.powerName"
          :value="power.id"
        >
         
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    
    <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">添加</el-button>
        <el-button @click="resetForm(formRef)">取消</el-button>
    </el-form-item>
    
    </el-form>
    </el-drawer>
    <el-drawer
        size="30%"
        v-model="drawer2"
        :title="'修改角色'"
        direction="rtl"
        :before-close="closeDrawer2">
            <el-form
            size="small"
            ref="formRef2"
            style="max-width: 600px"
            :model="formData2"
            status-icon
            :rules="rules"
            label-width="60px"
        >

    <el-form-item v-if="false" label="id" prop="id" >
        <el-input  v-model="formData2.id"  style="width: 300px;"  type="password"/>
    </el-form-item>
    <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData2.roleName" style="width: 300px;" />
    </el-form-item>
    <el-form-item label="选择权限" prop="powers">
      <el-checkbox-group v-model="formData2.powers">
        <el-checkbox
          v-for="power in allPowerList"
          :key="power.id"
          :label="power.powerName"
          :value="power.id"
        >
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="submitForm2(formRef2)">修改</el-button>
        <el-button @click="resetForm2(formRef2)">取消</el-button>
    </el-form-item>
    
    
    </el-form>
    </el-drawer>
</template>

<script setup lang="ts">
import { ElNotification } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ref,reactive, onMounted } from "vue";
import {$add,$findRole,$updateRole,$findAllPower} from '../../api/role.ts'

const emit = defineEmits(['sync-list'])

//抽屉变量
const drawer = ref(false)
//关闭抽屉
const closeDrawer = () =>{
    drawer.value =false
    //重置表单
    formRef.value?.resetFields()
    //清空表单
    formData.value = {
      roleName:'',
      powerList:[],
    }
}

//抽屉变量
const drawer2 = ref(false)
//关闭抽屉
const closeDrawer2 = () =>{
    drawer2.value =false
    //重置表单
    formRef2.value?.resetFields()
    //清空表单
    formData2.value = {
      id:'',
      roleName:'',
      powers:[],
    }
}

const formRef2 = ref<FormInstance>()

//表单数据
const formData2 = ref({
  id:'',
  roleName: '',
  powers: [], 
})


const formRef = ref<FormInstance>()

//表单数据
const formData = ref({
  roleName: '',
  powerList: [] as string[], // 这里是一个字符串数组，存储选中的权限 ID
})


//权限列表
const allPowerList = ref([])

//加载角色列表
const loadPowerList = async()=>{
   let ret = await $findAllPower();
  //  roleList.value = data.t; // 确保 data 结构正确
    // roles.value = data.t
  allPowerList.value = ret.t
  
  
}

onMounted(()=>{
  loadPowerList()
})


//验证角色名称
const validateroleName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入角色名称'))
  } else {
    callback()
  }
}

//验证对象
const rules = reactive<FormRules<typeof formData>>({
  roleName: [{ validator: validateroleName, trigger: 'blur' }],
})



//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return

  formEl.validate(async (valid) => {
    // 首先检查是否已经存在该角色名
    // 如果角色名没有重复，执行插入操作
    if(valid){
       const submitData = {
        roleName: formData.value.roleName,
        powers: formData.value.powerList, // 权限列表将传递给后端
      };

      // 提交数据
      const ret = await $add(submitData);
      //  let ret = await $add(formData.value)
        if (ret.code === 2001) {
          ElNotification({
            title: '添加成功',
            message: '角色添加成功！',
            type: 'success',
          })
          //通知父组件更新列表
          emit('sync-list')
          //重置表单
          formRef.value?.resetFields()
        }else{
          ElNotification({
            title: '修改失败',
            message: '请联系管理员',
            type: 'error',
          })
        }
    }
   
    // let roleExists = await $findRole(formData.value)
    // if (roleExists.code ===2001) {
    //   // 如果角色名已存在，弹出提示
    //   ElNotification({
    //     title: '失败',
    //     message: '当前用户名已存在',
    //     type: 'error',
    //   })
    //   return // 终止后续插入操作
    // }
    // if (valid) {
    //   //判断是做修改还是添加
    //   if(formData.value.id){
    //     let ret = await $updateRoleName(formData.value)
    //     if (ret.code === 2001) {
    //       ElNotification({
    //         title: '修改成功',
    //         message: '角色修改成功！',
    //         type: 'success',
    //       })
    //       //通知父组件更新列表
    //       emit('sync-list')
    //       //重置表单
    //       formRef.value?.resetFields()
    //     }else{
    //       ElNotification({
    //         title: '修改失败',
    //         message: '请联系管理员',
    //         type: 'error',
    //       })
    //     }
    //   }else{
        
      
    // }
      
      
     else {
      console.log('error submit!')
    }
  })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
   //清空表单
    formData.value = {
      roleName:'',
      powerList: [] as string[], // 这里是一个字符串数组，存储选中的权限 ID
    }
}

//提交表单2
const submitForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return

  formEl.validate(async (valid) => {
    // 首先检查是否已经存在该角色名
    // 如果角色名没有重复，执行插入操作
    if(valid){
      // let roleExists = await $findRole(formData2.value)
      // if (roleExists.code ===2001) {
      //   // 如果角色名已存在，弹出提示
      //   ElNotification({
      //     title: '失败',
      //     message: '当前用户名已存在',
      //     type: 'error',
      //   })
      //   return // 终止后续插入操作
      // }
      let ret = await $updateRole(formData2.value)
      if (ret.code === 2001) {
        ElNotification({
          title: '修改成功',
          message: '角色修改成功！',
          type: 'success',
        })
        //通知父组件更新列表
        emit('sync-list')
        //重置表单
        formRef.value?.resetFields()
      }else{
        ElNotification({
          title: '修改失败',
          message: '请联系管理员',
          type: 'error',
        })
      }
    } else {
      console.log('error submit!')
    }
})
}

//重置表单
const resetForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
   //清空表单
    formData2.value = {
      id:'',
      roleName: '',
      powers: [], // 这里是一个字符串数组，存储选中的权限 ID
    }
}

//暴露成员
defineExpose({
    drawer,
    formData,
    drawer2,
    formData2
})

</script>

<style lang="scss" scoped>

</style>